package demo.Socket_learn.Socket_talk;

import java.io.*;
import java.net.Socket;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/16-08-16-9:52
 * @Description：demo.Socket_learn.Socket_talk  客户端
 */
//客户端发送数据
public class TCP_Client {
    public static void main(String[] args) {
        Socket socket = null;
        BufferedReader reader = null;
        BufferedReader reader2 = null;
        PrintWriter printWriter = null;
        try {
            socket = new Socket("127.0.0.1",6666);
            String str,str1;
            //客户端从控制台读数据
            reader2 = new BufferedReader(new InputStreamReader(System.in));
            while((str = reader2.readLine()) != null){
                //客户端写数据
                //printWriter.println("hello,服务器！");
                printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                printWriter.println(str);
                printWriter.flush();

                //客户端接收数据
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                str1 = reader.readLine();
                System.out.println( "服务端: " + str1);
                System.out.flush();

            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(socket != null){
                    socket.close();
                }
                if(reader != null){
                    reader.close();
                }
                if(reader2 != null){
                    reader2.close();
                }
                if(printWriter != null){
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
